﻿using Abp.AspNetCore.Mvc.Controllers;
using Abp.Domain.Repositories;
using Batman.Cms.Core.Models.Mvc;
using Batman.Core;
using Batman.Jianbei.Forum.Core.Consts;
using Batman.Jianbei.Forum.Core.Domains;
using Batman.Jianbei.Forum.Core.Domains.Users;
using Batman.Jianbei.Forum.DTOS.Admin;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading.Tasks;

namespace Batman.Jianbei.Forum.Areas.Admin
{
    [Area(RouteNames.Admin)]
    public class AccountController : AbpController
    {
        public UserManager<User> UserManager { get; set; }

        public IRepository<WeixinUser, string> weixinUserRepo { get; set; }

        /// <summary>
        /// 根据账号Id获取账号信息简单部分
        /// </summary>
        /// <param name="accountId"></param>
        /// <returns></returns>
        public async Task<IActionResult> SimpleAccount(string accountId)
        {
            var simpleAccount = await UserManager.Users.AsNoTracking().Select(t => new IdNameDTO
            {
                Id = t.Id,
                Name = t.UserName
            }).FirstOrDefaultAsync(t => t.Id == accountId);

            return Json(simpleAccount);
        }

        /// <summary>
        /// 账号绑定微信
        /// </summary>
        /// <param name="accountId"></param>
        /// <returns></returns>
        [Authorize]
        public async Task<IActionResult> BindWeixin(string accountId)
        {
            ResponseBase result;
            var simpleAccount = await UserManager.Users.AsNoTracking().Select(t => new IdNameDTO
            {
                Id = t.Id,
                Name = t.UserName
            }).FirstOrDefaultAsync(t => t.Id == accountId);

            if (simpleAccount == null)
            {
                result = new ResponseBase(404, "要绑定的用户不存在");
                return Json(result);
            }

            var uid = User.GetWxUserId();
            var weixinUser = weixinUserRepo.GetQuery().Where(t => t.Id == uid).FirstOrDefault();
            if (weixinUser == null)
            {
                result = new ResponseBase(404, "微信未登陆");
                return Json(result);
            }

            if (!string.IsNullOrEmpty(weixinUser.UserId))
            {
                result = new ResponseBase(404, "该用户已绑定微信，若要重新绑定，请先解绑");
                return Json(result);
            }

            weixinUserRepo.Update(uid, t => t.UserId = accountId);

            return Json(new ResponseBase());
        }
    }
}
